var $projectManageList=$("#projectManage");
var $approverTabList=$("#approverTab")
var editCompany='';
$(function () {
    loadAllCompanyList()
    billNameFun('billCompany')
    projectManageFun()
    approverTabListFun()
    //添加开票公司

})

function indexFormat(value, row, index) {
    return index + 1;
}
function genderOptPro(value, row, index) {
    let html = '';
    html += '<button type="button" class="btn btn-default" id="editPro">修改</button>';
    html += '<button type="button" class="btn btn-default" id="deletTdInv">删除</button>';


    return html
}
var editInfoPro={
    //修改
    'click #editPro': function(e, value, row, index){
        editCompany=row.companyId
        $("#projectModels").modal('show')
        $("#projectModels h4").text('修改项目')
        $("#projectName").val(row.projectName)
        $("#companySelect").val(row.companyId)
        $('#companySelect').selectpicker('refresh');
        $("#taxRate").val(row.taxRate)
        $("#taxClassNumber").val(row.taxClassNumber)

        $("#companyProjectId").val(row.companyProjectId)
        // /companyProject/updateCompanyProject
    },
    //删除
    'click #deletTdInv': function(e, value, row, index) {
        let dataCom={
            companyId:row.invoiceCompanyId
        }
        $.confirm({
            title: '提示',
            content: '您确认要删除吗？',
            buttons: {
                ok: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function() {
                        $.ajax({
                            url: '/companyProject/delCompanyProject?companyProjectId='+row.companyProjectId,
                            type: 'POST',
                            contentType: "application/json;charset=utf-8",
                            // data:JSON.stringify(dataCom),
                            dataType:"json",
                            success:function (result) {
                                if(result.code=='000000'){
                                    $.alert('删除成功')
                                    $projectManageList.bootstrapTable('refresh')
                                }else{
                                    $.alert('删除失败')
                                }
                            },
                            error:function (res) {
                                $.alert('删除失败')
                            }
                        })
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'btn-default'
                }
            }
        })

    },


}
//table
function projectManageFun(){
    $projectManageList.bootstrapTable('destroy');
    $projectManageList.bootstrapTable({
        //table table-bordered table-hover table-striped
        classes: 'table table-hover table-bordered table-striped',
        url: '/companyProject/selectCompanyProjectList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: false,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'logId',
        idField: 'logId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[10]",//可供选择的每页的行数



        queryParams: function (params) {
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;

            // params.bs=0;
            return params;
        },//查询参数
        columns: [
            {title: '主键', field: 'logId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '60', formatter: indexFormat},
            {title: '项目名称', field: 'projectName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            //
            {title: '税率', field: 'taxRate', align: 'left', valign: 'middle'},
            {title: '税收分类编码', field: 'taxClassNumber', align: 'left', valign: 'middle'},


            {title: '操作', field: 'operate', align: 'right',events: editInfoPro, formatter:genderOptPro}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

//所属分公司
function loadAllCompanyList() {

    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">全部</option>';
            data.data.map(function (item) {

                if(editCompany==item.companyId){
                    companyOptionHtml += '<option value="' + item.companyId + '" selected>' + item.companyName + '</option>';
                }else{
                    companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
                }

            });
            $("#companySelect").html("");
            $('#companySelect').append(companyOptionHtml);
            $('#companySelect').selectpicker('refresh');
        }
    });
}

//新增提交
function addProjectCompany() {

    $('.add-project-company').bootstrapValidator({
        excluded: [":disabled"],
        fields: {
            projectName: {
                validators: {
                    notEmpty: {
                        message: '项目名称不能为空'
                    }
                }
            },
            companySelect:{
                validators: {
                    notEmpty: {
                        message: '所属分公司不能为空'
                    }
                }
            },

            taxRate: {
                validators: {
                    notEmpty: {
                        message: '税率不能为空'
                    }
                }
            },
            taxClassNumber: {
                validators: {
                    notEmpty: {
                        message: '税收分类编码不能为空'
                    }
                }
            },



        }
    })

    var bootstrapValidator = $(".add-project-company").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    let jsonData={
        projectName:$("#projectName").val(),
        companyId:$("#companySelect").val(),
        taxRate:$("#taxRate").val(),
        taxClassNumber:$("#taxClassNumber").val(),

    }
    //新增
    if($("#projectModels h4").html()=='新增项目'){
        $.ajax({
            type:"post",
            url:"/companyProject/addCompanyProject",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            dataType: 'json',
            async:false,
            success:function (data,status) {
                if(data.code=='000000'){
                    $.alert(data.message);
                    $("#projectModels").modal('hide')
                    $projectManageList.bootstrapTable('refresh')
                }else{
                    $.alert(data.message);
                }
            },
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    }else{
        jsonData['companyProjectId']=$("#companyProjectId").val()
        $.ajax({
            type:"post",
            url:"/companyProject/updateCompanyProject",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            dataType: 'json',
            async:false,
            success:function (data,status) {
                if(data.code=='000000'){
                    $.alert(data.message);
                    $("#projectModels").modal('hide')
                    $projectManageList.bootstrapTable('refresh')
                }else{
                    $.alert(data.message);
                }
            },
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    }

}

function addPro() {
    $("#projectModels").modal('show')
    $("#projectModels h4").text('新增项目')
    $("#projectName").val('')
    $("#companySelect").val('')
    $('#companySelect').selectpicker('refresh');
    $("#taxRate").val('')
    $("#taxClassNumber").val('')

    if($(".add-project-company").data('bootstrapValidator')!=undefined){
        $(".add-project-company").data('bootstrapValidator').destroy();
        $('.add-project-company').data('bootstrapValidator', null);
    }

}

//设置审核人


function genderOptApprover(value, row, index) {
    let html = '';
    html += '<button type="button" class="btn btn-default" id="editApprover">修改</button>';
    html += '<button type="button" class="btn btn-default" id="deletTdApprover">删除</button>';


    return html
}

var editInvoiceCompanyId=''
var editInfoApprover={
    //修改
    'click #editApprover': function(e, value, row, index){
        // $(this).parent().parent().remove()

        editInvoiceCompanyId=row.invoiceCompanyId
        $("#invoiceCompanyInfoId").val(row.invoiceCompanyInfoId)
        $("#billModels").modal('show')
        $("#billModels h4").text('修改审核人')
        $("#billCompany").val(row.invoiceCompanyId)
        $('#billCompany').selectpicker('refresh');
        $("#reviewer").val(row.reviewer)
        $("#makePerson").val(row.makePerson)
        $("#payee").val(row.payee)

        $("#companyProjectId").val(row.companyProjectId)
    },
    //删除
    'click #deletTdApprover': function(e, value, row, index) {

        $.confirm({
            title: '提示',
            content: '您确认要删除吗？',
            buttons: {
                ok: {
                    text: '确认',
                    btnClass: 'btn-primary',
                    action: function() {
                        $.ajax({
                            url: '/sysInvoiceCompanyInfo/delInvoiceCompanyInfo?invoiceCompanyInfoId='+row.invoiceCompanyInfoId,
                            type: 'POST',
                            contentType: "application/json;charset=utf-8",
                            // data:JSON.stringify(dataCom),
                            dataType:"json",
                            success:function (result) {
                                if(result.code=='000000'){
                                    $.alert('删除成功')
                                    $approverTabList.bootstrapTable('refresh')
                                }else{
                                    $.alert('删除失败')
                                }
                            },
                            error:function (res) {
                                $.alert('删除失败')
                            }
                        })
                    }
                },
                cancel: {
                    text: '取消',
                    btnClass: 'btn-default'
                }
            }
        })

    },


}
//table 设置审核人
function approverTabListFun(){
    $approverTabList.bootstrapTable('destroy');
    $approverTabList.bootstrapTable({
        //table table-bordered table-hover table-striped
        classes: 'table table-hover table-bordered table-striped',
        url: '/sysInvoiceCompanyInfo/selectInvoiceCompanyInfo',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: false,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'logId',
        idField: 'logId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[10]",//可供选择的每页的行数



        queryParams: function (params) {
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;

            // params.bs=0;
            return params;
        },//查询参数
        columns: [
            {title: '主键', field: 'logId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '60', formatter: indexFormat},
            {title: '复核人', field: 'reviewer', align: 'left', valign: 'middle'},
            {title: '开票人', field: 'makePerson', align: 'left', valign: 'middle'},
            {title: '收款人', field: 'payee', align: 'left', valign: 'middle'},
            {title: '开票公司', field: 'invoiceCompanyName', align: 'left', valign: 'middle'},
            //



            {title: '操作', field: 'operate', align: 'right',events: editInfoApprover, formatter:genderOptApprover}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function billNameFun(name) {
    let data_bill={
        companyStatus:0
    }
    //JSON.stringify()
    $.ajax({
        type:"post",
        url:"/sysInvoiceCompany/selectInvoiceCompanyList",

        data: data_bill,
        dataType: 'json',
        async:false,
        success:function (data,status) {

            if(data.code=='000000'){
                // var data_company=data.data
                let billNameOptionHtml = '<option value="">请选择</option>';
                data.data.map(function (item) {
                    if(editInvoiceCompanyId==item.invoiceCompanyId){
                        billNameOptionHtml += '<option value="' + item.invoiceCompanyId + '" selected>' + item.companyName + '</option>';
                    }else{
                        billNameOptionHtml += '<option value="' + item.invoiceCompanyId + '">' + item.companyName + '</option>';
                    }

                });
                // $('#'+name).html("");
                // $('#'+name).html(billNameOptionHtml);
                // $('#'+name).selectpicker('refresh');
                $('#'+name).html("");
                $('#'+name).append(billNameOptionHtml);
                $('#'+name).selectpicker('refresh');
            }else{
                $.alert(data.message);
            }
        },
        error: (function (res) {
            $.alert("保存失败");
        })
    })
}




function approverAddSubmit() {
    $('.bill-form').bootstrapValidator({
        excluded: [":disabled"],
        fields: {
            billCompany: {
                validators: {
                    notEmpty: {
                        message: '开票公司不能为空'
                    }
                }
            },
            reviewer:{
                validators: {
                    notEmpty: {
                        message: '复核人不能为空'
                    }
                }
            },

            makePerson: {
                validators: {
                    notEmpty: {
                        message: '开票人不能为空'
                    }
                }
            },
            payee: {
                validators: {
                    notEmpty: {
                        message: '收款人不能为空'
                    }
                }
            },


        }
    })

    var bootstrapValidator = $(".bill-form").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    let jsonData={
        //invoiceCompanyId invoiceCompanyInfoId
        invoiceCompanyId:$("#billCompany").val(),
        payee:$("#payee").val(),
        reviewer:$("#reviewer").val(),
        makePerson:$("#makePerson").val(),

    }
    //新增
    if($("#billModels h4").html()=='新增审核人'){
        $.ajax({
            type:"post",
            url:"/sysInvoiceCompanyInfo/addInvoiceCompanyInfo",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            dataType: 'json',
            async:false,
            success:function (data,status) {
                if(data.code=='000000'){
                    $.alert(data.message);
                    $("#billModels").modal('hide')
                    $approverTabList.bootstrapTable('refresh')
                }else{
                    $.alert(data.message);
                }
            },
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    }else{
        jsonData['invoiceCompanyInfoId']=$("#invoiceCompanyInfoId").val()
        $.ajax({
            type:"post",
            url:"/sysInvoiceCompanyInfo/updateInvoiceCompanyInfo",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            dataType: 'json',
            async:false,
            success:function (data,status) {
                if(data.code=='000000'){
                    $.alert(data.message);
                    $("#billModels").modal('hide')
                    $approverTabList.bootstrapTable('refresh')
                }else{
                    $.alert(data.message);
                }
            },
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    }
}

//add
function companyAdd() {
    $("#billModels").modal('show')
    $("#billModels h4").text('新增审核人')
    $("input").val('')
    $("select").val('')
    $('select').selectpicker('refresh');
    if($(".bill-form").data('bootstrapValidator')!=undefined){
        $(".bill-form").data('bootstrapValidator').destroy();
        $('.bill-form').data('bootstrapValidator', null);
    }
}

